import pymysql
from loguru import logger

def get_database_name(client_name):
    """
    根据客户名称获取数据库名称
    """
    if client_name == "富通东方":
        database_name = "futong"
    elif client_name == "安徽大众":
        database_name = "avw"
    elif client_name == "慧思拓":
        database_name = "hst"
    elif client_name == "慧思拓测试库":
        database_name = "hst_test"
    elif client_name == "voc测试库":
        database_name = "voc_test"
    else:
        logger.error("数据库名称错误")
        return None
    return database_name

def get_connection(client_name, db_type):
    database_name = get_database_name(client_name)
    print(f"数据库名称：{database_name}")
    conn = None
    try:
        if db_type == "data_query":  # 数据处理数据库
            conn = pymysql.connect(
                host='172.16.80.16',
                port=30120,
                user='voc',
                password='futong2024',
                database='voc',
                cursorclass=pymysql.cursors.DictCursor,
                charset='utf8mb4'
            )
        elif db_type == "rule_query":  # 规则数据库
            conn = pymysql.connect(
                host='172.16.80.16',
                port=30101,
                user='voc',
                password='voc2024.',
                database=database_name,
                cursorclass=pymysql.cursors.DictCursor,
                charset='utf8mb4'
            )
        elif db_type == "mysql_query":  # mysql测试环境数据库
            conn = pymysql.connect(
                host='172.16.80.16',
                port=31101,
                user='voc',
                password='voc2024.',
                database=database_name,
                cursorclass=pymysql.cursors.DictCursor,
                charset='utf8mb4'
            )
        elif db_type == "starrockets_query":  # starrockets测试环境数据库
            conn = pymysql.connect(
                host='172.16.80.16',
                port=31120,
                user='voc',
                password='futong2024',
                database=database_name,
                cursorclass=pymysql.cursors.DictCursor,
                charset='utf8mb4'
            )
        elif db_type == "starrockets_dev_query":  # starrockets测试开发环境数据库
            conn = pymysql.connect(
                host='172.16.80.16',
                port=30120,
                user='voc',
                password='futong2024',
                database=database_name,
                cursorclass=pymysql.cursors.DictCursor,
                charset='utf8mb4'
            )
        else:
            logger.error("数据库类型错误")
            return None

        logger.info("数据库连接成功")
        cursor = conn.cursor()  # cursor 对象允许你执行SQL语句并获取结果
        logger.info("游标创建成功")
        logger.info("数据库初始化完成")

    except Exception as e:
        logger.error(f"数据库连接失败: {e}")
        return None

    return conn


def execute(self, sql):
    self.cursor.execute(sql)
    self.conn.commit()
    results = self.cursor.fetchall()
    logger.info("执行sql语句成功")
    return results


def close(self):
    self.cursor.close()
    self.conn.close()
    logger.info("数据库连接关闭")

class DatabaseOperations:

    def connect(self,client_name, db_type):
        self.client_name = client_name
        self.db_type = db_type
        print(f"数据库连接中...{self.client_name} {self.db_type}" )
        self.conn = get_connection(self.client_name, self.db_type)

    def execute_query(self, sql):
        try:
            with self.conn.cursor() as cursor:  # cursor 对象允许你执行SQL语句并获取结果，使用with后自动关闭游标
                # 使用cursor.execute()执行一个语句
                cursor.execute(sql)
                return cursor.fetchall()
        except Exception as e:
            # 如果出现错误，回滚事务
            self.conn.rollback()
            print(f"异常sql--》 {sql}")
            print(f"An error occurred: {e}")

    def close_connection(self):
        if self.conn:
            self.conn.close()

if __name__ == "__main__":
    print("测试")
    conn = DatabaseOperations()
    conn.connect("富通东方","rule_query")
    sql = f"""select * from ins_channel where name = '默认分类' limit 1"""
    print(conn.execute_query(sql))
    conn.close_connection()

# ins_regulation_detail  规则详情表
# ins_regulation_info   规则表
